<?php

if(!defined('IN_ADAGPS'))
{
    die(SYSTEM_ACCESS_DENIED);
}
$objXajax->registerFunction('msfrmmanagerkara_loadMenu');      
$objXajax->registerFunction('msfrmmanagerkara_loadGrid');      
$objXajax->registerFunction('msfrmmanagerkara_checkedRoom');

$objXajax->registerFunction('msfrmmanagerkara_addRemoveProduct');
$objXajax->registerFunction('msfrmmanagerkara_moveRoom');
$objXajax->registerFunction('msfrmmanagerkara_loadProduct');
$objXajax->registerFunction('msfrmmanagerkara_finishRoom');

$objXajax->registerFunction('msfrmmanagerkara_addNewProduct');
$objXajax->registerFunction('msfrmmanagerkara_ajxTotalRoom');
$objXajax->registerFunction('msfrmmanagerkara_undo');
$objXajax->registerFunction('msfrmmanagerkara_loadRoom');
$objXajax->registerFunction('msfrmmanagerkara_rentRoom');
$objXajax->registerFunction('msfrmmanagerkara_showBill');
/*
* Hàm dùng để load sản phâm cho left menu 
* 
*/
function msfrmmanagerkara_loadMenu(){     

    global $lang,$arrMenu,$arrdetail;
    $objResponse = new xajaxResponse();
    $arr = array();
    $arrMain = msfrmmanagerkara_getMenu($arr,$arrdetail); 
      
    $oTbs = new clsTinyButStrong();
    $oTbs ->LoadTemplate("../templates/$lang/$path/ka_managerkara_menu_grid.html");
    $oTbs->MergeBlock('blk_list', $arrMain);
    $oTbs->MergeBlock('blk_list1', 'array', 'arrdetail[%p1%]');
        
    $objResponse->addAssign('msfrmmanagerkara_leftmenu', 'innerHTML', $oTbs->Source);
     
    $count = count($arr);
    for($i=0;$i<$count;$i++){ // tạo mãng tên và giá cho sản phẩm
        $name     = $arr[$i]['name'];
        $price    = $arr[$i]['price'];
        $id       = $arr[$i]['id'];
        $unit     = $arr[$i]['unit'];
        $unitname = $arr[$i]['unitname'];
        $objResponse->addScript("ka_obj.createAssignProductPrice($id,'$name','$price','$unit','$unitname');"); 
    }
    $indexNewProduct = time();
    $objResponse->addScript("ka_obj.indexNewProduct=$indexNewProduct;");                            
   // $objResponse->addScriptCall("ka_addJsContext();");  
    $objResponse->addScript("msfrmmanagerkara_dropdrapmenu();");                           
     $objResponse->addScript('$("div.ka_divProduct").droppable("disable");');                           
     //$objResponse->addScript('$("div.ka_divProduct").droppable("disable");');                           
    return $objResponse->getXML();
}

function msfrmmanagerkara_loadRoom(){ 
    global $lang,$arrDetail;
        $objResponse = new xajaxResponse();// dong luon luon co khi goi ham ajax
        $arrDetail = msfrmmanagerkara_getRoomInit();
        for($i=0;$i<count($arrDetail);$i++){
            $id = $arrDetail[$i]['id'];
            $name = $arrDetail[$i]['name'];
            $type = $arrDetail[$i]['type_id'];            
            $timestamp = $arrDetail[$i]['timestamp'];
            $current_id = $arrDetail[$i]['current_id']==''?0:$arrDetail[$i]['current_id'];
            $status = $timestamp>0?1:0;
            if($status==1){
                $objResponse->addScript("msfrmmanagerkara_ActiveStatus($id);"); 
            }
            $objResponse->addScript("ka_obj.createAssignRoomObj($id,'$name',$type,$status,$timestamp,$current_id);"); 
        }
        $objResponse->addScript('kaAssignTime();');
    return $objResponse->getXML(); // dong luon luon co khi goi ham ajax   
}

function msfrmmanagerkara_loadGrid(){     

    global $lang,$arrMenu,$arrDetail,$path;
    $objResponse = new xajaxResponse();// dong luon luon co khi goi ham ajax
    $arrDetail = array();
    $arrRoom = msfrmmanagerkara_getRoom($arrDetail);   

    $oTbs = new clsTinyButStrong();    
    $oTbs->LoadTemplate('../templates/'.$lang.'/'.$path.'/ka_managerkara_grid.html');   
    $oTbs->MergeBlock('blk_total', $arrRoom); 
    
    $oTbs->MergeBlock('blk_data', 'array', 'arrDetail[%p1%]'); 
    
   // $oTbs->MergeBlock('blk_data', $arrRoom);
    $oTbs->Show(TBS_NOTHING);
    $objResponse->addAssign('msfrmmanagerkara_divGrid', 'innerHTML', $oTbs->Source);
    $objResponse->addScript("addJsContext();");  
            
   $objResponse->addScript('$(".clsbtn_kara").button();');          
   $objResponse->addScript('$(".ka_chkHide").button();');          
   $objResponse->addScript('xajax_msfrmmanagerkara_loadMenu();');           
   $objResponse->addScript('xajax_msfrmmanagerkara_loadRoom();');          
   $objResponse->addScript('xajax_msfrmmanagerkara_loadProduct();');          
    return $objResponse->getXML(); // dong luon luon co khi goi ham ajax   
}

function  msfrmmanagerkara_getRoom(&$arrDetail){
    global $objDbSelect,$tbl_postfix;
    $arrResult = array();
    $sqlSelect = "SELECT r.id,r.room_type,r.name,t.style as color,t.name  as name_type,t.id as type_id
    FROM ka_room$tbl_postfix as r join ka_room_type$tbl_postfix  as t on r.room_type=t.id  order by r.room_type,r.name";
   // echo $sqlSelect; die();
    $arr =  $objDbSelect->GetArray($sqlSelect);
    for($i=0;$i<count($arr);$i++){
        $type_id = $arr[$i]['type_id'];
        $arrResult[$type_id]= array('type_id'=>$arr[$i]['type_id'],'name_type'=>$arr[$i]['name_type']);
        $arrDetail[$type_id][]=array('id'=>$arr[$i]['id'],'color'=>$arr[$i]['color'],'name'=>$arr[$i]['name']);
    }
    return $arrResult;
}
/*
*hàm này dùng để lấy danh sách bảng lên để lưu vào mãng 
* 
*/
function  msfrmmanagerkara_getRoomInit(){
    global $objDbSelect,$tbl_postfix;
    $arrResult = array();
    $sqlSelect = "SELECT r.id,r.room_type,r.name,t.style ,t.name  as name_type,t.id as type_id,c.id as current_id,if(c.timestart is not null or c.timestart <> '',TIMESTAMPDIFF(SECOND,c.timestart,now()),0) as timestamp
    FROM ka_room$tbl_postfix as r join ka_room_type$tbl_postfix  as t on r.room_type=t.id left join 
    ka_current_book$tbl_postfix as c on c.room_id = r.id and c.flgcal = 0 order by r.room_type,r.name";
    $arr =  $objDbSelect->GetArray($sqlSelect);
    return $arr;
}
    

function msfrmmanagerkara_getMenu(&$arr,&$arrDetail){
    global $objDbSelect,$lang,$tbl_postfix;    
    $sql = "select p1.name_$lang as name,p1.price as price,p1.unit,p1.unitname,p1.id,p1.product_type ,p2.name_$lang as parentname ,p2.icon,p1.parent_id
        from ka_product$tbl_postfix as p1 join ka_product$tbl_postfix as p2 on p1.parent_id
    = p2.id and p2.active = 1 where  p1.active = 1 order by p1.parent_id,p1.product_type " ;
    $arr = $objDbSelect->GetArray($sql);
    $count = count($arr);
    $arrResult = array();
    $index =-1;  
    $strresult='';
    $arrResult = array();
    for($i=0;$i<$count;$i++){
        $name = $arr[$i]['name'];
        $price = $arr[$i]['price'];
        if($arr[$i]['product_type']==0){
            $arrResult[$arr[$i]['parent_id']] = array('name'=>$name);
        }else{
            $arrDetail[$arr[$i]['parent_id']][]=array('name'=>$name,'id'=>$arr[$i]['id'],'price'=>$price);
        }
    }
    return $arrResult;
}
                                           
function msfrmmanagerkara_addRemoveProduct($arrAddRemove,$arrProduct=''){
     global $lang,$arrMenu,$objDbSelect;
     $objResponse = new xajaxResponse();
    // echo '<pre>'; print_r($arrAddRemove);die();
     for($i=0;$i<count($arrAddRemove);$i++){
         $temp = $arrAddRemove[$i];
         $arrId = explode(';',$temp);
         $product_id = $arrId[0];
         $nump = $arrId[2];
         $general_id = $arrId[1];
         msfrmmanagerkara_actionDB($general_id,$product_id,$nump,$arrProduct) ;
     }    
    
     return $objResponse->getXML();    
}

function msfrmmanagerkara_actionDB($general_id,$product_id,$nump,$arrProduct){
  global $objDbSelect,$tbl_postfix,$user_id;
       $sqlSelect = "select num from ka_history_product$tbl_postfix where general_id =  
     '$general_id' and product_id = '$product_id'";
     $arrSelect = $objDbSelect->GetArray($sqlSelect);
     $sql ='';
     if(is_array($arrSelect) && count($arrSelect)==1){
         $curnum =  $arrSelect[0]['num'];// số sản phẩm đã có hiện tại
         $nextnum = $curnum + $nump;
         if($nextnum<1){
             $sql= "delete from ka_history_product$tbl_postfix where general_id =  
     'general_id' and product_id = '$product_id'  ";     
     // write log........................
         }else{
            $sql = "update ka_history_product$tbl_postfix SET num = '$nextnum' where general_id =  
     '$general_id' and product_id = '$product_id' ";     
      // write log........................ 
         }
     }else{
        $name = $arrProduct[$product_id]['name'];
        $price = $arrProduct[$product_id]['price'];
        $sql = "insert into ka_history_product$tbl_postfix(general_id,product_id,name,price,date_created,user_created,num) 
        values('$general_id','$product_id','$name','$price',now(),'$user_id',$nump)"; 
       // write log........................   
     }    
     $objDbSelect->Execute($sql);  
}

function msfrmmanagerkara_moveRoom($RoomFrom,$RoomTo,$typeFrom,$typeTo){
    global $objDbSelect,$tbl_postfix,$user_id;
    $objResponse = new xajaxResponse();
    $update = '';
    if($typeFrom!=$typeTo){
        $update = ",timestart = now()";
        $sqlselect = " select id as general_id,timestart as timefrom,now() as timeto, TIMESTAMPDIFF(MINUTE,timestart,now()) as renttime from ka_current_book$tbl_postfix where room_id = '$RoomFrom' and flgcal = 0 ";
        $arr =  $objDbSelect->GetArray($sqlselect);
        $timefrom  = $arr[0]['timefrom'];
        $timeto    = $arr[0]['timeto'];
        $general_id    = $arr[0]['general_id'];
        $renttime    = $arr[0]['renttime'];
        $price     = ka_calTotal($timefrom,$timeto,$typeFrom);
        $sql = " insert into tbl_history_move$tbl_postfix(general_id, room_id, user_created, date_created, price, timestart,renttime)
        values($general_id,$RoomFrom,$user_id,now(),'$price','$timefrom',$renttime) ";
        $objDbSelect->Execute($sql); 
    }
    $sql = " update ka_current_book$tbl_postfix set room_id = $RoomTo ,user_update = '$user_id', date_update = now() $update where room_id  = $RoomFrom and flgcal = 0 ";

    $objDbSelect->Execute($sql);     
    return $objResponse->getXML();  
}
/*
* Hàm này dùng để load product lên các bàn 
* 
* 
*/
function msfrmmanagerkara_loadProduct(){
    global $objDbSelect,$tbl_postfix;
     $objResponse = new xajaxResponse();
    $sql = "select c.room_id,p.name,p.price,p.num,p.product_id from ka_history_product$tbl_postfix as p
JOIN ka_current_book$tbl_postfix as c ON c.id = p.general_id and c.flgcal = 0 order by p.date_created"; // lấy các sản phẩm có trên bàn từ DB
    $arr = $objDbSelect->GetArray($sql);
   // $objResponse->addScript("msfrmmanagerkara_dropdrapmenu();");
    for($i=0;$i<count($arr);$i++){
        $room_id = $arr[$i]['room_id'];
        $name = $arr[$i]['name'];
        $num = $arr[$i]['num'];
        $price = $arr[$i]['price'];
        $product_id = $arr[$i]['product_id'];
        $objResponse->addScript("msfrmmanagerkara_loadProduct('$room_id','$product_id','$name','$num','$price');"); // load các sản phẩm đó lên bàn
    }
  //  
    
    $objResponse->addScript("ka_addJsContext();");
    $objResponse->addScript("ka_calActiveTableByTableType();");
   // 
    
   return $objResponse->getXML();  
}
/*
* hàm này dùng để tính toán khi khách hàn kêu tính tiền  
* @room_id : id của bàn cần tính 
* $current_id : id đi của bàn mướn hiện hành
* $pricehour : tiền giờ
* $pricetotal : toàn bộ tiền của phòng
*/
function msfrmmanagerkara_finishRoom($current_id,$pricehour,$pricetotal,$room_id){    
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    //$general_id = time();
    $priceproduct =$pricetotal-$pricehour ;
    $sql = " update ka_current_book$tbl_postfix SET timeend=now(),flgcal =1,money_rent='$pricehour',total='$pricetotal',user_update = $user_id, date_update = now() where id = $current_id";
   // echo $sql; die();
    if($objDbSelect->Execute($sql)){
        $objResponse->addScript("$('#msfrmmanagerkara_divprint').dialog('close');");
        $objResponse->addScript("msfrmmanagerkara_DeactiveStatus($room_id);");
        $objResponse->addScript("ka_obj.resetRoom($room_id);");
        $objResponse->addScript("$('#msfrmmanagerkara_div_$room_id').find('.trProduct').remove();");
    }
    $objResponse->addScript("ka_calActiveTableByTableType();");
    return $objResponse->getXML();
}
/*
* Hàm này dùng để add sản phẩm ngoài doanh mục 
* $proId : lấy id từ indexproduct
* $hdtRoom : id của bàn thêm sản phẩm mới
* $name : tên sản phẩm 
* $price : giá của sản phẩm ngoài doanh mục
*/
function msfrmmanagerkara_addNewProduct($proId,$hdRoom,$name,$price,$general_id=''){
    global $objDbSelect,$user_id,$hotel_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sql =''; 
   
    if($general_id ==''){
        $sqlsel = "select id from ka_current_book$tbl_postfix where room_id = '$hdRoom' and flgcal = 0 " ;
        $arr = $objDbSelect->GetArray($sqlsel);
        $general_id = $arr[0]['id'];
    }
    $sql = "insert into ka_history_product$tbl_postfix(product_id,name,price,date_created,user_created,num,general_id) 
    values('$proId','$name','$price',now(),'$user_id',1,'$general_id')";  
     $objDbSelect->Execute($sql);  
    return $objResponse->getXML();    
}

function msfrmmanagerkara_undo($room_id){
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    
    $sqlgeneral = " select max(id) as general_id,TIMESTAMPDIFF(SECOND,max(timestart),now()) as renttime 
    from ka_current_book$tbl_postfix where room_id=$room_id group by room_id ";
    $arrgeneral = $objDbSelect->GetArray($sqlgeneral);
    $timestamp = $arrgeneral[0]['renttime'];
    //echo $timestamp;die();
    $general_id = $arrgeneral[0]['general_id'];
    
    $sql = "select * from ka_history_product$tbl_postfix where  general_id = $general_id order by date_created"; // lấy các sản phẩm có trên bàn từ DB   
    $objResponse->addScript("ka_obj.arrRoom[$room_id].status=1;"); 
    $objResponse->addScript("ka_obj.arrRoom[$room_id].timestamp=$timestamp;"); 
    $objResponse->addScript("ka_obj.arrRoom[$room_id].current_id=$general_id;"); 
   
    $arr = $objDbSelect->GetArray($sql);
    $sqlUpdate = "update ka_current_book$tbl_postfix set flgcal = 0,timeend=null,money_rent=0,total=0 where id = $general_id ";
    $objDbSelect->Execute($sqlUpdate);
    if(is_array($arr) && count($arr)>0){
      for($i=0;$i<count($arr);$i++){
        $name = $arr[$i]['name'];
        $num = $arr[$i]['num'];
        $price = $arr[$i]['price'];
        $product_id = $arr[$i]['product_id'];
        $objResponse->addScript("msfrmmanagerkara_loadProduct('$room_id','$product_id','$name','$num','$price');"); // load các sản phẩm đó lên bàn  
     }  
    }
    $objResponse->addScript("ka_calActiveTableByTableType();");
    $objResponse->addScript("msfrmmanagerkara_ActiveStatus($room_id)");
    return $objResponse->getXML();    
}

function msfrmmanagerkara_rentRoom($roomId){
    global $objDbSelect,$user_id,$tbl_postfix;
    $objResponse = new xajaxResponse();
    $sql = "INSERT into ka_current_book$tbl_postfix(timestart, room_id, first_room, user_created, date_created) VALUE(now(),'$roomId','$roomId',$user_id,now())";    
    $objDbSelect->Execute($sql);
    $current = mysql_insert_id();    
    $objResponse->addScript("ka_obj.AssignStatusRoom($roomId,1,$current);"); 
    $objResponse->addScript("msfrmmanagerkara_ActiveStatus($roomId)"); 
    $objResponse->addScript("ka_calActiveTableByTableType();");
                              
    return $objResponse->getXML(); 
}

function msfrmmanagerkara_showBill($current_id,$Room_id){
    global $objDbSelect,$user_id,$tbl_postfix,$hourPay,$hourmoney,$total,$lang,$path;
    $objResponse = new xajaxResponse();
   
    $sqlhour = "select c.timestart,now() as timeend,r.room_type,TIMESTAMPDIFF(SECOND,timestart,now()) as renttime from ka_current_book$tbl_postfix c join ka_room$tbl_postfix r on c.room_id = r.id where c.id = '$current_id'";
   // echo 
    $arrhour = $objDbSelect->GetArray($sqlhour);
    $from = $arrhour[0]['timestart'];
    $to = $arrhour[0]['timeend'];
    $room_type_id = $arrhour[0]['room_type'];
    $renttime = $arrhour[0]['renttime'];
    $hourPay=ConvertToHM($renttime);    
    $hourmoney = ka_calTotal($from,$to,$room_type_id);
   // echo $hourmoney; die();
    //echo "ka_calTotal($from,$to,$room_type_id)";die();
    
    $sql="SELECT  name, num, price * num as total,0 as style FROM ka_history_product$tbl_postfix where general_id = '$current_id' ";
    $arr = $objDbSelect->GetArray($sql);
    $counttemp = count($arr);
    $sqlHistorymove = " select r.name, h.renttime,h.price,1 as style from ka_history_move$tbl_postfix as h join ka_room$tbl_postfix as r ON r.id = h.room_id where general_id = '$current_id' ";
    $arrhistory = $objDbSelect->GetArray($sqlHistorymove);
    //echo $sqlHistorymove;die();
    for($i=0;$i<count($arrhistory);$i++){
       $arr[$i+$counttemp]['name'] ='Tiền giờ bàn '. $arrhistory[$i]['name'];
       $arr[$i+$counttemp]['num'] = ConvertToHM($arrhistory[$i]['renttime']);
       $arr[$i+$counttemp]['total'] = $arrhistory[$i]['price'];
       $arr[$i+$counttemp]['style'] = $arrhistory[$i]['style'];
    }
    $priceproduct = 0;
    for($i=0;$i<count($arr);$i++){
        $priceproduct += (int)$arr[$i]['total'];
    }
    //echo '<pre>'; print_r();die();
    $total=$hourmoney+$priceproduct;
    $oTbs = new clsTinyButStrong();    
    $oTbs->LoadTemplate('../templates/'.$lang.'/'.$path.'/ka_managerkara_bill.html');   
    $oTbs->MergeBlock('blk_list', $arr); 
     
    $oTbs->Show(TBS_NOTHING);
    $objResponse->addAssign('msfrmmanagerkara_divprint', 'innerHTML', $oTbs->Source);
    $objResponse->addScript("$('#msfrmmanagerkara_divprint').dialog('open')");    
    return $objResponse->getXML();
}
    
?>
